//
//  CQstatus.swift
//  weibo
//
//  Created by chengqiang on 16/7/22.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit

class CQstatus: NSObject {
    /// 微博ID
    var id: Int64 = 0
    
    /// 微博创建时间
    var created_at: String?
    
    /// 微博信息内容
    var text: String?
    
    /// 微博来源
    var source: String?{
        didSet{
            if let s = self.source{
                if s.characters.count == 0{
                    source = "来自＊＊"
                    return
                }
                let nsSouce = s as NSString
                let firstRange = nsSouce.rangeOfString(">")
                let lastRange = nsSouce.rangeOfString("</")
                let range = NSRange(location: firstRange.location+1, length: lastRange.location-firstRange.location-1)
                source = nsSouce.substringWithRange(range)
            }else{
                source = "来自＊＊"
            }
        }
    }
    
    /// 微博配图    // [Int] , [String: AnyObjcet] -> [[String: AnyObjcet]]
    var pic_urls: [[String: AnyObject]]?{
        didSet{
            if pic_urls?.count == 0 {
                return
            }
            storepicutureURLs=[NSURL]()
            for dict in pic_urls!{
                let urlString = dict["thumbnail_pic"] as?String
                let url = NSURL(string: urlString!)
                storepicutureURLs?.append(url!)
            }
            
        }
    }
    
    //  直接存放图片的URL
    var storepicutureURLs:[NSURL]?
    
    /// 转发数
    var reposts_count: Int = 0
    
    /// 评论数
    var comments_count: Int = 0
    
    /// 表态数
    var attitudes_count: Int = 0
    
    var user:CQUser?{
        didSet{
            
        }
    }
    
    //被转发微博模型  
    var retweeted_status :CQstatus?
    //被转发微博拼接好的文字
    var reteeeText:String?
    //行高
    var rowHeight:CGFloat = 0
    
    //计算行高
    private func calcRowHeight(){
        var height = CellMargin + CellMargin + CellIconWH + CellMargin
        if let text = self.text{
            let nsText = text as NSString
            //计算蚊子宽高
            height += nsText.boundingRectWithSize(CGSize(width: UIScreen.width()-2*CellMargin,height:CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(CellFontSize)], context: nil).height
        }
        //计算原创配图
        height += CellMargin
        let count = storepicutureURLs?.count ?? 0
        //有配图计算配图高度
        if count > 0 {
            height += callPictureSize(retweeted_status?.storepicutureURLs).height
            height += CellMargin
        }
        //判断是否有被转发的微博
        if let retweeted_status = self.retweeted_status{
            //有被转发的微博
            height += CellMargin
            
            //被转发的微博文字高度，被转发微博文字加了用户名称的
            let nsRetweetText = retweeted_status.reteeeText! as NSString
            height += nsRetweetText.boundingRectWithSize(CGSize(width: UIScreen.width()-2*CellMargin,height:CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(CellFontSize)], context: nil).height
            height += CellMargin
            //被转发配图
            let retweetCount = retweeted_status.storepicutureURLs?.count ?? 0
            if retweetCount > 0 {
                height += callPictureSize(retweeted_status.storepicutureURLs).height
                height += CellMargin
            }
        }
        //底部高度
        height += CellBottomViewHeight
        
        self.rowHeight = height
    }
    //计算配图的高度
    private func callPictureSize(imageUrls:[NSURL]?)->CGSize{
        //获取图片数量
        let count = imageUrls?.count ?? 0
        //总列数  默认三列
        var numberOfColimn = maxOfColumn
        if count == 1{
            numberOfColimn = 1
        }else if count == 2||count == 4{
            numberOfColimn = 2
        }
        if count == 0 {
            return CGSizeZero
        }
        //计算款度＝ 总列数＊图片的宽度＋（总列数－1）＊图片的间距
        let width = CGFloat(numberOfColimn)*StatusPictureViewItemWH + (CGFloat(numberOfColimn)-1)*itemMargin
        let numberOfrow = (count + numberOfColimn - 1)/numberOfColimn
        
        //计算高度＝ 总行数＊图片高度 ＋（总行数－1）＊图片的间距
        let height = CGFloat(numberOfrow)*StatusPictureViewItemWH + (CGFloat(numberOfrow)-1)*itemMargin
        return CGSize(width: width, height: height)
        
    }
    
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        self.calcRowHeight()
    }

    
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String:AnyObject]
            {
                user = CQUser(dict: dict)
            }
            return
        }
        //被转发微博
        if key=="retweeted_status"{
            if let dict = value as?[String:AnyObject]{
                retweeted_status = CQstatus(dict: dict)
                //拼接完整的被转发微博内容
                let name = retweeted_status?.user?.screen_name ?? "没有名称"
                let text = retweeted_status?.text ?? "没有微博内容"
                let context = "@\(name):\(text)"
                retweeted_status?.reteeeText = context
            }
            return
        
        }
        super.setValue(value, forKey: key)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override var description: String{
        get {
            let keys=["id", "created_at", "text", "source", "pic_urls", "reposts_count", "comments_count", "attitudes_count","user"]
            return "\n\n 微博模型： " + dictionaryWithValuesForKeys(keys).description
        }
    }

}
